<template>
  <div style="height:100%;">
    <van-form @submit="onSubmit" v-loading="loading" style="height:100%;">
      <div style="height: calc(100% - 178px);padding-top: 20px;overflow-y: scroll;">
        <div v-if="pushBackExist" style="height: 60px;">
          <van-cell v-for="item in pushBackList"
                    :title="'退回信息：'+item.text" :label="item.creat_time"
                    style="color: #EE0A24;font-size: 16px;"/>
        </div>

        <template v-for="item in ffItemList" v-if="item.ee_show">
          <van-field v-if="item.type=='input' || item.type=='text'"
                     :readonly="!item.ee_edit"
                     :placeholder="item.ee_edit?'请输入':''"
                     :type="!item.e_number?'number':'text'"
                     v-model="item.f_value" :name="item.title" :label="item.title"
                     :style="v_f_style">
          </van-field>

          <van-field v-if="item.type=='select' || item.type=='datetime' || item.type=='date' || item.type=='time'"
                     :name="item.title" :label="item.title"
                     :style="v_f_style">
            <template #input>
              <div v-if="em(item.f_value) && item.ee_edit" style="float: left;margin-top: 0px;color: #CECFD2;">请选择</div>
              <div style="float: left;margin-top: 0px;">{{item.f_value}}</div>
              <div style="float: right">
                <van-image v-if="item.type=='select' && item.ee_edit" width="14" height="14"
                           src="/images/mob-icon-vf-01.svg"
                           @click="showItemEdit(item)" style="margin-left: 10px;"/>
                <van-image v-if="(item.type=='datetime' || item.type=='date' || item.type=='time') && item.ee_edit" width="14" height="14"
                           src="/images/mob-icon-vf-02.svg"
                           @click="showItemEdit(item)" style="margin-left: 10px;"/>
              </div>
            </template>
          </van-field>
          <van-popup v-model="itemEditShow" position="bottom" style="height: 100%;" closeable :overlay="false"
                     @open="itemEditOpened" @close="itemEditClosed">
            <div :style="{'margin-top':'40px','width':ss_width}">
              <van-datetime-picker v-if="itemEditData.type=='date'"
                                   v-model="itemEditData.f_value" @confirm="itemEdit_setValue" @cancel="itemEditClosed"
                                   type="date" title="选择日期" :min-date="minDate"/>
              <van-datetime-picker v-if="itemEditData.type=='time'"
                                   v-model="itemEditData.f_value" @confirm="itemEdit_setValue" @cancel="itemEditClosed"
                                   type="time" title="选择时间" :min-date="minDate"/>
              <van-datetime-picker v-if="itemEditData.type=='datetime'"
                                   v-model="itemEditData.f_value" @confirm="itemEdit_setValue" @cancel="itemEditClosed"
                                   type="datetime" title="选择日期时间" :min-date="minDate"/>

              <van-picker v-if="itemEditData.type=='select'"
                          :default-index="itemEditData.f_value_history" :columns="itemEditData.list"
                          @confirm="itemEdit_setValue" @cancel="itemEditClosed"
                          title="选择" show-toolbar />
            </div>
          </van-popup>

          <van-field v-if="item.type=='select_ei'" :name="item.title" :label="item.title"
                     :style="v_f_style">
            <template #input>
              <span v-if="false">{{item.f_value}}</span>
              <elm-mob-ei v-model="item.f_value" :disabled="!item.ee_edit"></elm-mob-ei>
            </template>
          </van-field>
          <van-field v-if="item.type=='select_org'" :name="item.title" :label="item.title"
                     :style="v_f_style">
            <template #input>
              <span v-if="false">{{item.f_value}}</span>
              <elm-mob-org v-model="item.f_value" :disabled="!item.ee_edit"></elm-mob-org>
            </template>
          </van-field>
          <van-field v-if="item.type=='select_car'" :name="item.title" :label="item.title"
                     :style="v_f_style">
            <template #input>
              <span v-if="false">{{item.f_value}}</span>
              <elm-mob-car v-model="item.f_value" :disabled="!item.ee_edit"></elm-mob-car>
            </template>
          </van-field>
          <van-field v-if="item.type=='file'" :name="item.title" :label="item.title"
                     :style="v_f_style_file">
            <template #input>
              <elm-upload v-if="item.ee_edit" :ref="item.column_name"
                          style="margin-left: 10px;float: right;" :multiple="true" :limit="10" list-type="file" tip=" "
                          module_name="item.file_module_name" :rel_id="model.id"
                          :is_mob="true"></elm-upload>
              <elm-fileview v-if="!item.ee_edit" style="margin-left: 10px;margin-top: -5px;" :multiple="true" list-type="file" tip=""
                            module_name="item.file_module_name" :rel_id="model.id"></elm-fileview>
            </template>
          </van-field>
          <elm-mob-cost-type v-if="item.type=='bx_item'" :f_title="item.title" :ref="bx_item_id" :biz_id="model.id" :page_type="page_type"
                             :disabled="!item.ee_edit"></elm-mob-cost-type>
          <elm-mob-select v-if="item.type=='select_input_xs'" v-model="item.f_value" url="/business/my/GetLeadData" label="线索" title="线索"
                          key-name="select_id" label-name="select_name" value-name="select_id" size="mini"
                          :disabled="!item.ee_edit">
          </elm-mob-select>
          <elm-mob-select v-if="item.type=='select_input_sj'" v-model="item.f_value" url="/business/my/GetOppoData" label="商机" title="商机"
                          key-name="select_id" label-name="select_name" value-name="select_id" size="mini"
                          :disabled="!item.ee_edit">
          </elm-mob-select>
          <elm-mob-select v-if="item.type=='select_input_pu'" v-model="item.f_value" url="/business/my/GetPuData" label="采购" title="采购"
                          key-name="select_id" label-name="select_name" value-name="select_id" size="mini"
                          :disabled="!item.ee_edit">
          </elm-mob-select>
          <elm-mob-select v-if="item.type=='select_input_pj'" v-model="item.f_value" url="/business/my/GetPjData" label="项目" title="项目"
                          key-name="select_id" label-name="select_name" value-name="select_id" size="mini"
                          :disabled="!item.ee_edit">
          </elm-mob-select>
        </template>
      </div>
      <div v-if="!readonly" style="height: 100px;padding-top: 48px;margin-left: 20px;margin-right: 20px;">
        <van-button block type="info" native-type="submit"
                    style="height: 42px;font-size: 18px;color:#ffffff;background-color:#028aff;border-radius: 4px;">
          提交</van-button>

        <van-button v-if="page_type=='edit' && allowPushBack"
                    block plain type="danger" native-type="button" @click="showPushBack"
                    style="height: 42px;font-size: 18px;color:#ffffff;background-color:#f46d6d;border-radius: 4px;border-color:#f46d6d;margin-top: 15px;">
          退回</van-button>
        <van-popup v-model="pushBackShow" position="left" style="height: 100%;width: 100%;" :overlay="false">
          <div style="margin-top: 40px;">
            <van-field v-model="pb_text" name="退回意见" label="退回意见" placeholder="请输入">
            </van-field>

            <div style="padding-top: 48px;margin-left: 20px;margin-right: 20px;">
              <van-button v-if="page_type=='edit'"
                          block plain type="danger" native-type="button" @click="PushBack"
                          style="height: 42px;font-size: 18px;color:#ffffff;background-color:#f46d6d;border-radius: 4px;border-color:#f46d6d;margin-top: 15px;">
                确定</van-button>
            </div>
          </div>
        </van-popup>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading:true,

      model:{},
      upsert_url:'/system/login/flow/FlowsecFormItem_Upsert',

      ffItemList:[],

      v_f_style:{
        'height':'48px',
        'font-size':'14px',
        'color':'#505968',
        //'text-align':'right',
      },
      v_f_style_file:{
        'font-size':'14px',
        'color':'#505968',
        //'text-align':'right',
      },

      itemEditShow:false,
      itemEditId:null,
      itemEditData:{},

      allowPushBack:false,
      pushBackShow:false,
      pb_text:'',

      pushBackExist:false,
      pushBackList:[],

      bx_item_id: 'bx_item_'+ new Date().getTime(),

      ss_width:((document.body.clientWidth) - 25)+'px',

      minDate: new Date(2025, 0, 1),
    }
  },
  props: {
    flow_code: { type: String, default: null },
    data_id: { type: String, default: null },
    nodeins_id: { type: String, default: null },
    page_type: { type: String, default: null },//create、edit
    pb_flag: { type: String, default: null },
    readonly: { type: Boolean, default: false },
  },
  watch: {
    pb_flag: {
      handler(newval, oldval) {
        if (newval != null && newval!='' && newval!=oldval) {
          if(newval=='no'){
            this.pushBackShow=false;
          }
        }
      },
      immediate: true
    },
  },
  created() {},
  mounted() {
    if(this.page_type=='create'){ this.model = {'id':elm.newGuid()}; }
    else{ this.model = {'id':this.data_id}; }

    this.minDate=new Date();

    this.load();
  },
  methods: {
    showPushBack:function(){
      this.pushBackShow = true;
      this.$emit('push_back_show', true);
    },
    showItemEdit:function(data){
      this.itemEditId = data.id;
      let itemEditData = {'type':data.type,'list':[],'f_value':null,f_value_history:null};
      console.log(itemEditData.type);

      if(itemEditData.type=='select'){
        let list = [];
        for(let i=0;i<data.s_item.length;i++){
          list.push(data.s_item[i].title);
          if(data.f_value==data.s_item[i].title){itemEditData.f_value_history=i;}
        }
        itemEditData.list = list;
      }
      else if(itemEditData.type=='date' || itemEditData.type=='datetime' || itemEditData.type=='time'){
        itemEditData.f_value = this.em(itemEditData.f_value)?new Date():new Date(itemEditData.f_value);
      }
      this.itemEditShow = true;
      this.itemEditData = itemEditData;
    },
    itemEditOpened:function(){
      console.log(JSON.stringify(this.itemEditData));
    },
    itemEditClosed:function(){
      this.itemEditId = null;
      this.itemEditData = {};
      this.itemEditShow = false;
    },
    itemEdit_setValue:function(value){
      for(let i=0;i<this.ffItemList.length;i++){
        let item = this.ffItemList[i];
        if(item.id == this.itemEditId){
          if( this.itemEditData.type=='select'){ item.f_value = value; }
          else if( this.itemEditData.type=='datetime'){ item.f_value = this.turnDate01(value); }
          else if( this.itemEditData.type=='date'){ item.f_value = this.turnDate02(value); }
          else if( this.itemEditData.type=='time'){ item.f_value = this.turnDate03(value); }
          else{}
        }
      }

      this.itemEditClosed();
    },

    async load(callback){
      this.loading = true;

      if(this.page_type!='create' && this.page_type!='edit'){this.$toast.fail('不支持的页类型');return;}

      if(this.page_type=='create'){
        if(this.em(this.flow_code)){this.$toast.fail('数据缺失，未能加载');return;}
      }
      else if(this.page_type=='edit'){
        if(this.em(this.flow_code) || this.em(this.data_id) || this.em(this.nodeins_id)){this.$toast.fail('数据缺失，未能加载');return;}
      }

      ///组装表单
      let ffItemList = [];
      let nItemList = [];
      let ppData = {
        'flow_code':this.flow_code,
        'nodeins_id':this.em(this.nodeins_id)?'nothing':this.nodeins_id,
        'type':this.page_type,
      };
      let fData = await elm.post('/system/login/flow/GetFlowsecFormItemByNodeinsId', ppData);
      let fList = fData.data;
      if(fData.node_data!=null && fData.node_data.length==1 && fData.node_data[0]!=null && !this.em(fData.node_data[0].ee_ff_item)){
        nItemList = JSON.parse(fData.node_data[0].ee_ff_item);
      }
      ffItemList = JSON.parse(fList[0].table_column);
      if(fList==null ||fList.length!=1){ this.$toast.fail('未找到表单模板'); return; }
      for(let i=0;i<ffItemList.length;i++){
        let item = ffItemList[i];
        item['file_module_name'] = this.flow_code+'_'+item.column_name;

        if(this.page_type=='edit'){
          //查询业务数据
          let ffData = await elm.post('/system/login/flow/FlowsecFormItem_SelectOne', {'flow_code':this.flow_code,'id':this.data_id});
          item.f_value = ffData[item.column_name];
        }

        item.ee_show = true;
        item.ee_edit = true;
        for(let kk=0;kk<nItemList.length;kk++){
          let nItem = nItemList[kk];
          if(nItem.column_name==item.column_name){
            item.ee_show = nItem.ee_show;
            item.ee_edit = nItem.ee_edit;
            kk =nItemList.length+1;
          }
        }
        if(this.readonly){item.ee_edit = false;}

      }
      //console.log(JSON.stringify(ffItemList));

      this.ffItemList = ffItemList;

      //检查是否允许退回
      let CheckPushBackAllow = await elm.post('/system/login/flow/CheckPushBackAllow', {'nodeins_id':this.nodeins_id});
      this.allowPushBack = CheckPushBackAllow=='yes';
      //查找退回记录
      this.pushBackExist = false;
      this.pushBackList = [];
      if(!this.em(this.nodeins_id)){
        let CheckPushBackInfo = await elm.post('/system/login/flow/SearchRunningPbtoNodeins', {'nodeins_id':this.nodeins_id});
        if(CheckPushBackInfo.length>0){
          for(let i=0;i<CheckPushBackInfo.length;i++){
            let item = CheckPushBackInfo[i];
            if(!this.em(item.sys_createtime)){
              item['creat_time'] = item.sys_createtime.split('T')[0];
            }
          }

          this.pushBackExist = true;
          this.pushBackList = CheckPushBackInfo;
        }
      }

      this.loading = false;
    },

    async onSubmit() {
      let f_check = true;
      for(let i=0;i<this.ffItemList.length;i++){
        let item = this.ffItemList[i];
        if(item.e_require && item.ee_show && item.ee_edit){
          if(item.type=='file'){
            item.f_value = null;
            if(this.$refs[item.column_name][0].fileNum>0){
              item.f_value = 'some';
            }
          }
          if(this.em(item.f_value)){
            this.$toast.fail(item.title+' 必须填写');
            f_check = false;
            i = this.ffItemList.length + 1;
          }
        }
      }
      if(!f_check){ return; }

      this.loading = true;

      //组装业务数据
      for(let i=0;i<this.ffItemList.length;i++){
        let item = this.ffItemList[i];
        this.model[item.column_name] = item.f_value;
      }
      this.model['flow_code'] = this.flow_code;
      //子表组装
      if (this.$refs[this.bx_item_id]) {
        this.model['reims'] = this.$refs[this.bx_item_id][0].reims;
      }

      //保存业务数据
      let result = await elm.post(this.upsert_url, this.model);
      //result = false;//测试用，仅保存数据，不提交流程
      if (result == true) {
        //提交流程
        if(this.em(this.nodeins_id)){//若无节点实例ID，那么发起流程
          let pData = {'flow_code':this.flow_code,'data_id':this.model.id};
          pData['token'] = elm.info.token;
          //pData['no_auto_next'] = '1';//测试用，阻止连续自动完成
          let data = await elm.post('/system/login/flow/InitFlow', pData);
          console.log('submit_initFlow'+JSON.stringify(data));
          if(data.status=='success'){
            if(data.data!=null && data.data.go_next_result!=null && data.data.go_next_result.message == 'flowOver'){
              this.$toast.success({ type: 'success', message: '提交成功，流程已结束' });
            }
            else{this.$toast.success({ type: 'success', message: '已发起流程并提交至下一环节' });}

            result='success';
          }
          else { this.$toast.fail('提交失败，请稍后尝试。'); result='failure'; }
        }
        else{//完成流程节点
          let pData = {'nodeins_id':this.nodeins_id};
          pData['token'] = elm.info.token;
          let data = await elm.post('/system/login/flow/CompleteNodeins', pData);
          console.log('submit_completeNodeins'+JSON.stringify(data));
          if(data.status=='success'){
            if(data.message == 'flowOver'){
              this.$toast.success({ type: 'success', message: '提交成功，流程已结束' });
            }
            else{this.$toast.success({ type: 'success', message: '已提交至下一环节' });}

            result='success';
          }
          else { this.$toast.fail('提交失败，请稍后尝试。'); result='failure';}
        }
      }
      else { this.$toast.fail('保存失败，请稍后尝试。'); }

      this.$emit('after_submit', result);
      this.loading = false;
    },
    async PushBack (){
      this.loading = true;

      let result = '';

      let pData = {'nodeins_id':this.nodeins_id,'pb_text':this.pb_text};
      pData['token'] = elm.info.token;
      let data = await elm.post('/system/login/flow/PushBackToNodeins', pData);
      console.log('submit_Pushback'+JSON.stringify(data));
      if(data.status=='success'){
        this.$toast.success({ type: 'success', message: '退回成功' });
        result='success';
      }
      else {
        this.$toast.fail({ type: 'success', message: '退回失败 '+data.message });
        result='failure';
      }

      this.$emit('after_submit', result);

      this.loading = false;
    },

    turnDate01:function(d){
      if(d==null || d.getFullYear==null){return '';}
      let year = d.getFullYear();
      let month = d.getMonth()+1;
      let day = d.getDate();
      let hour = d.getHours();
      let minute = d.getMinutes();
      let second = d.getSeconds();

      let s = year + '-' + this.addZero(month) + '-' + this.addZero(day) + ' '
          + this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
      return  s;
    },
    turnDate02:function(d){
      if(d==null || d.getFullYear==null){return '';}
      let year = d.getFullYear();
      let month = d.getMonth()+1;
      let day = d.getDate();

      let s = year + '-' + this.addZero(month) + '-' + this.addZero(day);
      return  s;
    },
    turnDate03:function(d){
      if(d==null || d.getFullYear==null){return '';}
      let hour = d.getHours();
      let minute = d.getMinutes();
      let second = d.getSeconds();

      let s = this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
      return  s;
    },
    addZero:function(s){ if((''+s).length==1){return ('0'+s);} else{return s;} },

    em: function (s) {
      if (s == null || s == '') { return true; }
      else { return false; }
    },
  }
}
</script>